﻿using KouDai.Core.Helper;
using KouDai.Core.Parser;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Core.Engine
{
    public class NetEngine : INetEngine
    {
        public async Task RequestAsync(CommunicationData commnunicationData)
        {
            await RequestAsync(commnunicationData, CancellationToken.None);
        }

        public async Task RequestAsync(CommunicationData communicationData,CancellationToken cancellationToken)
        {
            SendData sendData = communicationData.SendData;
            BackData backData = communicationData.BackData;
            try
            {
                //拼接参数
                Dictionary<string, object> body = communicationData.SendData.Body;
                EncryptType encryptType = communicationData.SendData.EncryptType;
                string data = BuildParams(encryptType, body);
                //组装url
                string proxyName = communicationData.SendData.ProxyName;
                string method = communicationData.SendData.Method.ToString();
                string url = BuildUrl(proxyName, method, data);
                //发送请求
                HttpEngine engine = new HttpEngine();
                byte[] resBytes = await engine.Request(url, method, data, cancellationToken);
                string jsonStr = Encoding.UTF8.GetString(resBytes, 0, resBytes.Length);
                //获取数据成功
                backData.IsSuccess = true;
                //解析
                KouDaiParser parser = communicationData.Parser;
                parser.ParseJson(jsonStr, communicationData);
            }
            catch (System.Exception ex)
            {
                backData.IsSuccess = false;
                Debug.WriteLine("错误:" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 拼接请求的parameters
        /// </summary>
        /// <param name="encryptType"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        private string BuildParams(EncryptType encryptType, Dictionary<string, object> body)
        {
            return encryptType == EncryptType.AES ? ParamHelper.EncryptParam(body) : ParamHelper.BuildParas(body);
        }

        /// <summary>
        /// 组装请求的url
        /// 如果是get请求则组装get 请求的字符串
        /// </summary>
        /// <param name="proxyName"></param>
        /// <param name="method"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string BuildUrl(string proxyName, string method, string data)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Constants.Host);
            sb.Append(proxyName);
            if (method.Equals("GET", StringComparison.CurrentCultureIgnoreCase))
            {
                sb.Append("?");
                sb.Append(data);
            }
            return sb.ToString();
        }

    }
}
